package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.CartBean;
import beans.CartItemBean;
import beans.ErrorBean;
import beans.ProductBean;
import beans.ProductList;

public class ShopDispatcher extends HttpServlet {

	private static String pageShop = null;
	private static String pageError = null;
	private static String pageDetail = null;

	/**
	 * Constructor of the object.
	 */
	public ShopDispatcher() {
		super();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init(ServletConfig config) throws ServletException {
		// Put your code here
		super.init(config);

		pageShop = config.getInitParameter("PAGE_SHOP");
		pageError = config.getInitParameter("PAGE_ERROR");
		pageDetail = config.getInitParameter("PAGE_DETAIL");
	}

	/**
	 * The processRequest method of the servlet. <br>
	 * 
	 * This method is called when a request is received
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");

		// module is not specified
		if (action == null) {
			action = "show";
		}

		// forward the request to the specific dispatcher.
		if (action.equals("show")) {
			String category = request.getParameter("category");
			String page = request.getParameter("page");
			if (category == null) {
				category = "All";
			}

			// According to the category, initiate the ProductList Bean
			ProductList products = new ProductList();
			products.setProductsByCategory(tools.Utility
					.ConvertCategory(category));

			// Add the page id into the request
			if (page == null) {
				page = "1";
			} else {
				try {
					int pageNum = Integer.parseInt(page);
					int productSize = products.getProducts().size();
					int quotient = productSize / 10;
					int remainder = productSize % 10;
					if (remainder != 0) {
						quotient++;
					}
					if (pageNum > quotient) {
						page = String.valueOf(quotient);
					}
					if (pageNum < 1) {
						page = "1";
					}
				} catch (Exception e) {
					page = "1";
				}
			}
			request.setAttribute("PAGE", page);
			request.setAttribute("PRODUCTS", products);

			request.getRequestDispatcher(pageShop + "?category=" + category)
					.forward(request, response);
		} else if (action.equals("detail")) {
			String productID = request.getParameter("id");
			try {
				int productNum = Integer.parseInt(productID);
				ProductBean product = new ProductBean();
				product.setId(productNum);
				if (product.setProductByID()) {
					request.setAttribute("PRODUCT", product);
					request.getRequestDispatcher(pageDetail).forward(request,
							response);
				}
			} catch (Exception e) {

			}
		} else if (action.equals("add")) {
			HttpSession session = request.getSession();

			if (session.getAttribute("CART") == null) {
				CartBean cart = new CartBean();
				session.setAttribute("CART", cart);
			}
			String number = request.getParameter("quantity");
			String productid = request.getParameter("productid");

			try {
				ProductBean product = new ProductBean();
				product.setId(Integer.parseInt(productid));
				product.setProductByID();

				CartItemBean item = new CartItemBean();
				item.setProduct(product);
				item.setNumber(Integer.parseInt(number));

				CartBean cart = (CartBean) session.getAttribute("CART");
				cart.add(item);

				session.setAttribute("CART", cart);
				
				String category = request.getParameter("category");
				String page = request.getParameter("page");

				request.getRequestDispatcher("/Dispatcher?mod=shop&action=show&category=" + category + "&page=" + page).forward(request,
						response);

			} catch (Exception e) {
				ErrorBean error = new ErrorBean();
				error.setMessage("Casting Exception");
				request.setAttribute("errorMessage", error);
				request.getRequestDispatcher("/error.jsp").forward(request,
						response);
			}

		}
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}
}
